//
//  RACNetworking.m
//  VET
//
//  Created by Lam on 16/7/1.
//  Copyright © 2016年 user. All rights reserved.
//

#import "RACNetworking.h"
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <AFNetworking/AFNetworking.h>
#import "AFHTTPSessionManager.h"
#import "AFHTTPSessionManager+PATCH.h"

@interface RACNetworking ()

@property (nonatomic ,strong) AFHTTPSessionManager *manager;

@end

NSString * const kHeaderKey = @"header-";

@implementation RACNetworking

SingletonM

- (instancetype)init {
    
    if (self = [super init]) {
        
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            
            self.manager = [AFHTTPSessionManager manager];
            [self configSerializer];
            // 是否携带 User-Agent 信息
//            NSString *userAgent = self.manager.requestSerializer.HTTPRequestHeaders[@"User-Agent"];
//            userAgent = [userAgent stringByReplacingOccurrencesOfString:@"tasker" withString:@"tasker-sfp"];
//            [self.manager.requestSerializer setValue:userAgent forHTTPHeaderField:@"User-Agent"];
        });
    }
    
    return self;
}

- (void)configSerializer {
    
    AFJSONRequestSerializer *reqSerializer = [AFJSONRequestSerializer serializer];
    [reqSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [reqSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    // 超时时间
    self.manager.requestSerializer.timeoutInterval = 30;
    // 请求压缩方式
    [self.manager.requestSerializer setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
    [self.manager.requestSerializer setValue:@"gzip" forHTTPHeaderField:@"Content-Encoding"];
    self.manager.requestSerializer = reqSerializer;
    
    AFJSONResponseSerializer *resSerializer = [AFJSONResponseSerializer serializer];
    [resSerializer setReadingOptions:NSJSONReadingAllowFragments | NSJSONReadingMutableContainers];
    resSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", @"application/json", nil];
    self.manager.responseSerializer = resSerializer;
}

#pragma mark - 网络请求

/*
 * 网络请求 - GET
 */
- (RACSignal*)getURL:(NSString*)url whitParams:(NSDictionary *)params {
    
    // 输出请求信息
    params = [self configNetInfo:url params:params];
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        
        [self.manager GET:url parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            // 成功回调
            [subscriber sendNext:responseObject];
            [subscriber sendCompleted];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            // 失败回调
            [subscriber sendError:error];
            [subscriber sendCompleted];
        }];
        
        return [RACDisposable disposableWithBlock:^{}];
    }];
}

// post 请求
- (RACSignal*)postURL:(NSString*)url whitParams:(NSDictionary *)params {
    
    // 输出请求信息
    params = [self configNetInfo:url params:params];
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        
        [self.manager POST:url parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            // 成功回调
            [subscriber sendNext:responseObject];
            [subscriber sendCompleted];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            // 失败回调
            [subscriber sendError:error];
            [subscriber sendCompleted];
        }];
        
        return [RACDisposable disposableWithBlock:^{}];
    }];
}

// put 请求
- (RACSignal*)putURL:(NSString*)url whitParams:(NSDictionary *)params {
    
    // 输出请求信息
    params = [self configNetInfo:url params:params];
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        
        [self.manager PUT:url parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            // 成功回调
            [subscriber sendNext:responseObject];
            [subscriber sendCompleted];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            // 失败回调
            [subscriber sendError:error];
            [subscriber sendCompleted];
        }];
        
        return [RACDisposable disposableWithBlock:^{}];
    }];
}

- (RACSignal*)patchURL:(NSString*)url whitParams:(NSDictionary *)params{
    params = [self configNetInfo:url params:params];
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        
        [self.manager PATCH:url parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            // 成功回调
            [subscriber sendNext:responseObject];
            [subscriber sendCompleted];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            // 失败回调
            [subscriber sendError:error];
            [subscriber sendCompleted];
        }];
        
        return [RACDisposable disposableWithBlock:^{}];
    }];
    
}

// delete 请求
- (RACSignal*)deleteURL:(NSString*)url whitParams:(NSDictionary *)params {
    
    // 输出请求信息
    params = [self configNetInfo:url params:params];
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        
        [self.manager DELETE:url parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            // 成功回调
            [subscriber sendNext:responseObject];
            [subscriber sendCompleted];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            // 失败回调
            [subscriber sendError:error];
            [subscriber sendCompleted];
        }];
        
        return [RACDisposable disposableWithBlock:^{}];
    }];
}

- (RACSignal*)uploadImgWithUrl:(NSString*)url params:(NSDictionary *)params img:(UIImage*)image imgPath:(NSString*)path apiKey:(NSString*)key {
    
    params = [self configNetInfo:url params:params];
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber){
        
        [self.manager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            
            NSData *imageData = UIImageJPEGRepresentation(image, .5);
            // 在网络开发中，上传文件时，是文件不允许被覆盖，文件重名
            // 要解决此问题，
            // 可以在上传时使用当前的系统事件作为文件名
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            // 设置时间格式
            [formatter setDateFormat:@"yyyyMMddHHmmss"];
            NSString *dateString = [formatter stringFromDate:[NSDate date]];
            NSString *fileName = [NSString  stringWithFormat:@"%@.jpg", dateString];
            /*
             *该方法的参数
             1. appendPartWithFileData：要上传的照片[二进制流]
             2. name：对应网站上处理文件的字段
             3. fileName：要保存在服务器上的文件名
             4. mimeType：上传的文件的类型
             */
            [formData appendPartWithFileData:imageData name:path fileName:fileName mimeType:@"image/jpeg"];
            
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            
            NSString *progressStr = [NSString stringWithFormat:@"%.2f", uploadProgress.fractionCompleted];
            NSDictionary *responseObject = @{@"progress" : progressStr, @"apiKey" : key};
            [subscriber sendNext:responseObject];
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            [subscriber sendNext:responseObject];
            [subscriber sendCompleted];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            [subscriber sendError:error];
            [subscriber sendCompleted];
        }];
        
        return [RACDisposable disposableWithBlock:^{}];
    }];
}

- (NSDictionary*)configNetInfo:(NSString*)url params:(NSDictionary *)params {
    
    NSMutableString *urlLink = [NSMutableString string];
    [urlLink appendFormat:@"%@?", url];
    [params.allKeys enumerateObjectsUsingBlock:^(NSString *key, NSUInteger idx, BOOL * _Nonnull stop) {
        [urlLink appendFormat:@"%@=%@&", key, params[key]];
    }];
    
    NSLog(@"请求地址：%@", url) ;
    NSLog(@"请求数据：%@", params);
    NSLog(@"请求链接：%@", urlLink);
    
    [self configSerializer];
    NSMutableDictionary *bodyParams = [NSMutableDictionary dictionary];
    for (NSString *key in params.allKeys) {
        
        if ([key hasPrefix:kHeaderKey]) {
            
            NSString *headerKey = [key substringFromIndex:kHeaderKey.length];
            [self.manager.requestSerializer setValue:params[key] forHTTPHeaderField:headerKey];
        } else {
            
            [bodyParams setObject:params[key] forKey:key];
        }
    }
    
    return bodyParams;
}

#pragma mark - 实时检测网络状态

+ (void)startMonitoring {
    
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        // 当网络状态改变时调用
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                NSLog(@"未知网络");
                break;
            case AFNetworkReachabilityStatusNotReachable:
                NSLog(@"没有网络");
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
            {
                NSString *netInfo = [NSString stringWithFormat:@"手机自带网络:%@", [[RACNetworking sharedInstance] getNetType]];
                NSLog(@"%@", netInfo);
            }
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                NSLog(@"WIFI");
                break;
        }
    }];
    
    //开始监控
    [manager startMonitoring];
}

+ (void)stopMonitoring {
    
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager stopMonitoring];
}

- (NSString *)getNetType {
    
    CTTelephonyNetworkInfo *info = [[CTTelephonyNetworkInfo alloc] init];
    NSString *currentStatus = info.currentRadioAccessTechnology;
    
    NSString *netconnType = @"";
    if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyGPRS"]) {
        
        netconnType = @"GPRS";
    }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyEdge"]) {
        
        netconnType = @"2.75G EDGE";
    }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyWCDMA"]){
        
        netconnType = @"3G";
    }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyHSDPA"]){
        
        netconnType = @"3.5G HSDPA";
    }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyHSUPA"]){
        
        netconnType = @"3.5G HSUPA";
    }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyCDMA1x"]){
        
        netconnType = @"2G";
    }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyCDMAEVDORev0"]){
        
        netconnType = @"3G";
    }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyCDMAEVDORevA"]){
        
        netconnType = @"3G";
    }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyCDMAEVDORevB"]){
        
        netconnType = @"3G";
    }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyeHRPD"]){
        
        netconnType = @"HRPD";
    }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyLTE"]){
        
        netconnType = @"4G";
    }
    
    return netconnType;
}

@end





